package com.linkage.jz.bankruptcy.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProTalkDetail;
import com.linkage.jz.bankruptcy.bean.ProTalkReply;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.utils.MenuBottomSheetDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author AFAP
 * 话题详情
 */
public class TalkDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private ProTalkDetail mTalkDetail = null;
    private List<ProTalkReply> mData;

    private boolean deleteReply = false;
    private boolean bannedDiscussion = false;

    public TalkDetailAdapter(Context context, List<ProTalkReply> datas) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
        mData = datas;
    }

    public void setDeleteReply(boolean deleteReply) {
        this.deleteReply = deleteReply;
    }

    public void setBannedDiscussion(boolean bannedDiscussion) {
        this.bannedDiscussion = bannedDiscussion;
    }

    public void setTalkDetail(ProTalkDetail talkDetail) {
        this.mTalkDetail = talkDetail;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 0) {
            View view = mLayoutInflater.inflate(R.layout.item_talk_detail, parent, false);
            return new TalkDetailViewHolder(view);
        } else {
            View view = mLayoutInflater.inflate(R.layout.item_talk_reply, parent, false);
            return new TalkReplyViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder0, final int position) {
        if (holder0 instanceof TalkDetailViewHolder) {
            if (mTalkDetail == null) {
                return;
            }
            TalkDetailViewHolder holder = (TalkDetailViewHolder) holder0;
            holder.tv_talk_title.setText(mTalkDetail.getSubjectTitle());
            holder.tv_creator_name.setText(mTalkDetail.getUser().getUsername());
            holder.tv_create_time.setText(DateFormatUtils.long2Str(mTalkDetail.getCreateTime(), true));
            holder.tv_talk_content.setText(mTalkDetail.getSubjectDescribe());
            holder.tv_reply.setText("回复：" + mData.size());

            Glide.with(mContext).load(mTalkDetail.getUser().getAvatar())
                    .bitmapTransform(new CropCircleTransformation(mContext))
                    .placeholder(R.drawable.logo)
                    .into(holder.img_creator_avatar);

            holder.area_imgs.removeAllViews();
            for (int i = 0; i < mTalkDetail.getAttachments().size(); i++) {
                TaskAtta atta = mTalkDetail.getAttachments().get(i);
                String fileName = atta.getAttachmentName();
                final String url = atta.getAttachmentWatermarkAddress();
                // 先加载图片
                if (FileUtil.isImage(fileName)) {
                    ImageView imageView = new ImageView(mContext);
                    imageView.setAdjustViewBounds(true);
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
                    imageView.setOnClickListener(view -> ImageShowActivity.start((Activity) mContext, url,
                            ImageShowActivity.FROM_SINGLE_SHOW));
                    holder.area_imgs.addView(imageView);
                    ImageLoader.getInstance().displayImage(url, imageView);
                }
            }
            for (int i = 0; i < mTalkDetail.getAttachments().size(); i++) {
                final TaskAtta atta = mTalkDetail.getAttachments().get(i);
                final String fileName = atta.getAttachmentName();
                final String url = atta.getAttachmentWatermarkAddress();
                // 再加载其他附件
                if (!FileUtil.isImage(fileName)) {
                    View v = View.inflate(mContext, R.layout.activity_pro_public_file_item, null);
                    TextView tv_file_name = v.findViewById(R.id.tv_file_name);
                    tv_file_name.setText(fileName);
                    v.setOnClickListener(view -> BaseActivity.openOrDownloadFile(atta, (Activity) mContext));
                    holder.area_imgs.addView(v);
                }
            }


            if (mData.size() == 0) {
                holder.area_no_reply.setVisibility(View.VISIBLE);
            } else {
                holder.area_no_reply.setVisibility(View.GONE);
            }
        } else if (holder0 instanceof TalkReplyViewHolder) {
            TalkReplyViewHolder holder = (TalkReplyViewHolder) holder0;

            final ProTalkReply reply = mData.get(position - 1);

            holder.tv_name.setText(reply.getUser().getUsername());
            holder.tv_time.setText(DateFormatUtils.long2Str(reply.getOpAt(), true));
            holder.tv_num.setText(position + "楼");
            holder.tv_content.setText(reply.getReplyContent());

            Glide.with(mContext).load(reply.getUser().getAvatar())
                    .bitmapTransform(new CropCircleTransformation(mContext))
                    .placeholder(R.drawable.logo)
                    .into(holder.img_avatar);
            if (bannedDiscussion || reply.auth.getDeleteReply()) {

                holder.img_avatar.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                            showReplyOperation(reply);

                        return false;
                    }
                });
                holder.tv_content.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                            showReplyOperation(reply);

                        return false;
                    }
                });
            }
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int getItemCount() {
        return mData.size() + 1;
    }

    class TalkDetailViewHolder extends RecyclerView.ViewHolder {

        private View area_no_reply;
        private TextView tv_talk_title, tv_creator_name, tv_create_time, tv_talk_content, tv_reply;
        private ImageView img_creator_avatar;
        private LinearLayout area_imgs;

        TalkDetailViewHolder(View view) {
            super(view);
            area_no_reply = view.findViewById(R.id.area_no_reply);
            tv_talk_title = view.findViewById(R.id.tv_talk_title);
            tv_creator_name = view.findViewById(R.id.tv_creator_name);
            tv_create_time = view.findViewById(R.id.tv_create_time);
            tv_talk_content = view.findViewById(R.id.tv_talk_content);
            tv_reply = view.findViewById(R.id.tv_reply);
            img_creator_avatar = view.findViewById(R.id.img_creator_avatar);
            area_imgs = view.findViewById(R.id.area_imgs);

        }
    }

    static class TalkReplyViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_name, tv_num, tv_time, tv_content;
        private ImageView img_avatar;

        TalkReplyViewHolder(View view) {
            super(view);
            tv_name = view.findViewById(R.id.tv_name);
            tv_num = view.findViewById(R.id.tv_num);
            tv_time = view.findViewById(R.id.tv_time);
            tv_content = view.findViewById(R.id.tv_content);
            img_avatar = view.findViewById(R.id.img_avatar);
        }
    }

    void showReplyOperation(final ProTalkReply reply) {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(mContext);

        if(bannedDiscussion) {
            dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("禁言", v -> {
                bannedReply(reply);
                dialog.dismiss();
            }));
        }
        if(reply.auth.getDeleteReply()) {
            dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("删除内容", v -> {
                deleteReply(reply);
                dialog.dismiss();
            }));
        }
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("取消", 0xffff5555, v -> dialog.dismiss()));
        dialog.show();
    }

    private void deleteReply(ProTalkReply reply) {
        if (!deleteReply) {
            ToastUtil.showShort("您没有删除回复权限");
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .deleteTalkReply(userToken, reply.getId())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TALK_REPLY);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("回复已删除");
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private void bannedReply(ProTalkReply reply) {
        if (!bannedDiscussion) {
            ToastUtil.showShort("您没有禁言权限");
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .bannedTalkReply(userToken, reply.getSubjectId(), reply.getCreditorId())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("用户已被禁言");
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

}
